﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using pTools.cMethods;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace pTools.ChildWin
{
    public partial class FuJuan : Form
    {
        string barId = "";
        cMethods.DBHelper db;
        HttpAgreement http;
        public FuJuan(string dataId)
        {
            InitializeComponent();
            barId = dataId;
            db = new cMethods.DBHelper();
            http = new HttpAgreement();
        }

        private void FuJuan_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = "生产复卷";
                tbQuPi.Text = "0";
                tbBarCodes.Text = barId;
                tbBarCodes.ReadOnly = true;
                loadMachine();
                loadPrintTemplte();
                loadBarInfo();
                PrintDocument fPrintDocument = new PrintDocument(); //获取默认打印机的方法
                cbPrint.Text = fPrintDocument.PrinterSettings.PrinterName;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        string unit = "";
        /// <summary>
        /// 加载条码数据
        /// </summary>
        private void loadBarInfo()
        {
            if (!string.IsNullOrWhiteSpace(barId))
            {
                var arr = barId.Split(',');
                string bars = "";
                foreach (string bar in arr)
                {
                    bars += "'" + bar + "',";
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_BarCode_Info where ");
                sb.Append("barCode in(" + bars.TrimEnd(',') + ")");
                var table = db.getData(sb.ToString(),"");
                if (table.Rows.Count > 0)
                {
                    if (table.Rows[0]["barStatus"].ToString() != "need-fj")
                    {
                        MessageBox.Show("该条码状态不允许复卷", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        btnPrint.Enabled = false;
                        return;
                    }
                    else
                    {
                        btnPrint.Enabled = true;
                    }
                    tbProCode.Text = table.Rows[0]["proCode"].ToString();
                    tbProName.Text = table.Rows[0]["proName"].ToString();
                    tbSpec.Text = table.Rows[0]["spec"].ToString();
                    tbWidth.Text = table.Rows[0]["width"].ToString();
                    tbthickness.Text = table.Rows[0]["thickness"].ToString();
                    tbMiShu.Text = table.Rows[0]["c_mishu"].ToString();
                    unit = table.Rows[0]["unit"].ToString();
                    tbProCode.ReadOnly = true;
                    tbProName.ReadOnly = true;
                    tbSpec.ReadOnly = true;
                    tbthickness.ReadOnly = true;
                    tbWidth.ReadOnly = true;
                    tbMiShu.ReadOnly = true;
                }
                else
                {
                    MessageBox.Show("条码信息不存在", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    btnPrint.Enabled = false;
                    return;
                }
            }
        }
        /// <summary>
        /// 打印模板
        /// </summary>
        private void loadPrintTemplte()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select lbCode,lbName from bar_PrintTemplates_list where status=1");
            // sb.Append(" and lType='" + lType + "'");
            var table = db.getData(sb.ToString(), "");
            cbTemplate.DataSource = table;
            cbTemplate.ValueMember = "lbCode";
            cbTemplate.DisplayMember = "lbName";
        }
        /// <summary>
        /// 机台信息
        /// </summary>
        private void loadMachine()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select cCode,cName from fun_CommonData_Info where isdel=0 ");
            sb.Append("and status='Y' and ctype='scjt' ");
            var table = db.getData(sb.ToString(), "");
            cbMachine.DataSource = table;
            cbMachine.ValueMember = "cCode";
            cbMachine.DisplayMember = "cName";
        }
        private void tbBarCodes_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                CommonMethods.SinglePar = "";
                if (e.KeyCode == Keys.Enter)
                {
                    FuJuanBars win = new FuJuanBars();
                    win.StartPosition = FormStartPosition.CenterScreen;
                    win.WindowState = FormWindowState.Normal;
                    if (win.ShowDialog() == DialogResult.OK)
                    {

                    }
                    if (!string.IsNullOrWhiteSpace(CommonMethods.SinglePar))
                    {
                        tbBarCodes.Text = CommonMethods.SinglePar;
                        barId = CommonMethods.SinglePar;
                        loadBarInfo();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                VisitService();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 打印接口访问
        /// </summary>
        private void VisitService()
        {

            Dictionary<string, string> barDic = new Dictionary<string, string>();
            barDic["proCode"] = tbProCode.Text;
            barDic["proName"] = tbProName.Text;
            barDic["printNum"] = "1";
            barDic["barType"] = "ys";
            barDic["isInitial"] = "N";
            if (cbInHouse.Checked)
            {
                barDic["barStatus"] = "need-in";
            }
            else
            {
                if (cbInHouse.Checked)
                {
                    barDic["barStatus"] = "need-in";
                }
                else
                {
                    barDic["barStatus"] = "";
                }
            }
            barDic["wareHouse"] ="";
            barDic["planCode"] = "";
            barDic["createuser"] = CommonMethods.userCode;
            barDic["proType"] = "sccp";
            barDic["unit"] = unit;
            barDic["number"] = tbJingZhong.Text;
            barDic["pUserCodes"] = CommonMethods.userPositionValue; ;//生产人员编码
            barDic["pusers"] = CommonMethods.userPositionTitle;//生产人员、岗位
            barDic["relationBar"] =tbBarCodes.Text;
            barDic["thickness"] = tbthickness.Text;
            barDic["width"] = tbWidth.Text;
            barDic["c_mishu"] = tbMiShu.Text;
            barDic["c_gongjin"] = tbWeight.Text;
            var msg = http.PostJson("SaveBarCode", JsonConvert.SerializeObject(barDic));
            if (!string.IsNullOrWhiteSpace(msg))
            {
                var json = JsonConvert.DeserializeObject<JObject>(msg);
                if (bool.Parse(json["Result"].ToString()))
                {
                    if (string.IsNullOrWhiteSpace(json["Data"].ToString()))
                    {
                        MessageBox.Show("接口返回数据异常，请联系开发人员", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    var table = CommonMethods.createPrintTable();
                    #region 填充表格数据
                    var r = table.NewRow();
                    r["proCode"] = tbProCode.Text;
                    r["proName"] = tbProName.Text;
                    r["width"] = tbWidth.Text;
                    r["number"] = tbWeight.Text;
                    r["thickness"] = tbthickness.Text;
                    r["unit"] = unit;
                    table.Rows.Add(r);
                    #endregion

                    if (cbIsPrint.Checked)
                    {
                        var arr = json["Data"].ToString().Split(',');
                        for (int i = 0; i < arr.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(arr[i]))
                            {
                                table.Rows[i]["barCode"] = arr[i];
                            }
                        }
                        string info = "";
                        var pResult = CommonMethods.DoPrint(table, cbTemplate.Text, cbPrint.Text, ref info);
                        if (!pResult)
                        {
                            MessageBox.Show("条码打印失败：" + info, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else
                    {
                        MessageBox.Show("条码打印成功：" + json["Data"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
                else
                {
                    MessageBox.Show(json["Message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("接口反馈异常", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tbUsers_Click(object sender, EventArgs e)
        {
            CommonMethods.selectUserCodes = "";
            CommonMethods.selectUserNames = "";
            selectPosition win = new selectPosition("");
            win.StartPosition = FormStartPosition.CenterScreen;
            win.WindowState = FormWindowState.Normal;
            if (win.ShowDialog() == DialogResult.OK)
            {

            }
            if (CommonMethods.userPositionTitle != null)
            {
                tbUsers.Text = CommonMethods.userPositionTitle;
            }
        }

        private void tbQuPi_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(tbWeight.Text))
                {
                    tbJingZhong.Text = Convert.ToString(double.Parse(tbWeight.Text) - double.Parse(tbQuPi.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tbWeight_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(tbWeight.Text))
                {
                    tbJingZhong.Text = Convert.ToString(double.Parse(tbWeight.Text) - double.Parse(tbQuPi.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tbBarCodes_Click(object sender, EventArgs e)
        {
            try
            {
                CommonMethods.SinglePar = "";

                FuJuanBars win = new FuJuanBars();
                win.StartPosition = FormStartPosition.CenterScreen;
                win.WindowState = FormWindowState.Normal;
                if (win.ShowDialog() == DialogResult.OK)
                {

                }
                if (!string.IsNullOrWhiteSpace(CommonMethods.SinglePar))
                {
                    tbBarCodes.Text = CommonMethods.SinglePar;
                    barId = CommonMethods.SinglePar;
                    loadBarInfo();
                }
              
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
